package com.seu.clab.farm.common.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.seu.clab.farm.util.ConstantUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

@Component
public class QCloudCOSClient {
    private COSClient cosClient;
    private String bucketName;
    private String bucketBaseUrl;

    @Autowired
    public QCloudCOSClient(
            QCLoudCOSBucketConfig qCloudCOSBucketConfig,
            QCloudCOSConfig qCloudCOSConfig
    ){
        COSCredentials cosCredentials = new BasicCOSCredentials(qCloudCOSConfig.secretId, qCloudCOSConfig.secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(qCloudCOSBucketConfig.regionString));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        cosClient = new COSClient(cosCredentials, clientConfig);
        bucketName = qCloudCOSBucketConfig.bucketName;
        bucketBaseUrl = qCloudCOSBucketConfig.bucketBaseUrl;
    }

    public String uploadFile(
            MultipartFile multipartFile
    ) throws IOException {
        // 获取文件名、后缀
        String fileBaseName = String.valueOf(ConstantUtil.generateId());
        String fileExtensionName = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(
                multipartFile.getOriginalFilename().lastIndexOf(".") + 1
        );
        String fileName = String.format("%s.%s", fileBaseName, fileExtensionName);
        File uploadFile = convertMultipartFileToFile(multipartFile, fileBaseName, fileExtensionName);
        // 路径格式为"后缀名/文件名"
        String path = String.format("%s/%s", fileExtensionName, fileName);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, uploadFile);
        cosClient.putObject(putObjectRequest);
        return String.format("%s/%s", bucketBaseUrl, path);
    }

    private File convertMultipartFileToFile(
            MultipartFile multipartFile,
            String fileBaseName,
            String fileExtensionName
    ) throws IOException {
        File file = File.createTempFile(fileBaseName, fileExtensionName);
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
        return file;
    }
}
